﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Contracts.Library
{

    /// <summary>
    /// Nicht typisierter Asynchronizer ohne Message
    /// </summary>
    public class Asynchronizer
    {

        /// <summary>
        /// Input
        /// </summary>
        public void Process()
        {
            if (OnProcessing == null)
                return;
            var thread = new Thread(() => OnProcessing());
            thread.Start();
        }

        /// <summary>
        /// Output
        /// </summary>
        public event Action OnProcessing;
    }


    /// <summary>
    /// Asynchrone Ausführung
    /// </summary>
    public class Asynchronizer<T>
    {
        
        private bool abortRunningProcesses;
        private Thread thread = null;

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="abortRunningProcesses">Beim Aufruf von Process kann ein laufender Process gestoppt werden</param>
        public Asynchronizer(bool abortRunningProcesses)
        {
            this.abortRunningProcesses = abortRunningProcesses;
        }

        /// <summary>
        /// Input
        /// </summary>
        /// <param name="message">Nachricht</param>
        public void Process(T message)
        {
            if (OnProcessing == null)
                return;

            if (thread != null && abortRunningProcesses)
            {
                thread.Abort();
                thread = null;
            }

            thread = new Thread(() => OnProcessing(message));
            thread.Start();
        }

        /// <summary>
        /// Output
        /// </summary>
        public event Action<T> OnProcessing;
       
    } 
}
